<template>
  <!--角色里的模块的操作按钮-->
  <el-checkbox
    style="width:85px"
    v-for="(item, index) in list"
    :key="'check' + index + '_' + item.buttonId"
    v-model="roleButton[item.buttonId]"
    @click="mychange($event, item.buttonId)"
  >
    {{item.label}}
  </el-checkbox>
</template>

<script lang="ts">
  import { defineComponent, reactive, watch } from 'vue'
  import { getRoleState } from '../state/state-role'
  
  /**
   * 角色的模块里的操作按钮
   * * 展现操作按钮，
   * * 设置按钮权限
   * * 绑定以及选的按钮权限
   */
  export default defineComponent({
    name: 'ui-core-',
    props: {
      moduleId: {
        type: [String, Number],
        default: 4
      }
    },
    setup(props, context) {

      const state = getRoleState()

      const list = state.buttons[props.moduleId]
      const roleButton = reactive({})

      // 如果有按钮，设置选项值
      if (list) {
        // 设置 check 的选项值
        list.forEach((item) => {
          roleButton[item.buttonId] = false
        })
      }

      // 监听选项值，设置角色
      watch(roleButton, () => {
        const arr = new Set([])
        list.forEach((item) => {
          if (roleButton[item.buttonId]) {
            // 选了，设置权限
            arr.add(item.buttonId)
          } else {
            arr.delete(item.buttonId)
          }
        })

        if (arr.length === 0) {
          delete state.roleInfo.rolePower.buttonIds[props.moduleId]
        } else {
          state.roleInfo.rolePower.buttonIds[props.moduleId] = Array.from(arr)
        }

      })

      // 监听模块是否被选中
      watch(state.roleInfo.rolePower.moduleIds, (ids: Array<string | number>) => {
        if (ids.includes(props.moduleId)) {
          if (list) {
            // 记录是否有选中的
            let hasCheck = false
            list.forEach((item) => {
              if (roleButton[item.buttonId]) {
                hasCheck = true
              }
            })

            if (!hasCheck) {
              list.forEach((item) => {
                roleButton[item.buttonId] = true
              })
            }
          }
        } else {
          // 去掉
          if (list) {
            list.forEach((item) => {
              roleButton[item.buttonId] = false
            })
          }
        }
      })

      const mychange = (e, buttonId) => {
        // console.log('change----e', buttonId, e)
        // 防止事件冒泡
        e.stopPropagation()

      }

      return {
        mychange,
        roleButton,
        list
      }
    }
  })
</script>